<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/01/05
 * Time: 18:23
 * @link http://www.lmterp.cn
 */

namespace app\common\behavior\check;

use app\common\model\JobFlowModule;
use app\common\model\Purchase;
use app\common\model\PurchaseReturn;
use app\common\service\product\StockService;
use think\Db;

/**
 * 采购退货审批回调
 * Class PurchaseReturnCheck
 * @package app\common\behavior\check
 */
class PurchaseReturnCheck extends BaseCheck
{

    /**
     * @inheritDoc
     */
    protected function execute()
    {
        $jobFlow = $this->getJobApprove();
        if($jobFlow->id_type != 'purchase_return') return;
        $ren = PurchaseReturn::get($jobFlow->ref_id);
        // 更新审批状态
        $this->updateCheckStatus($ren);
        // 审批完成占用库存
        if(JobFlowModule::isCheckFinish($ren)) $this->lockStock($ren);
    }

    /**
     * 占用库存
     * @param PurchaseReturn $ren 采购换货单
     * @return bool|string
     * @date 2021/01/05
     * @author longli
     */
    protected function lockStock($ren)
    {
        Db::startTrans();
        // 已上架占用库存
        if(in_array($ren->purchase->getData('order_status'), [Purchase::ORDER_STATUS_IN_PART, Purchase::ORDER_STATUS_IN_SUCC])
            && StockService::purchaseReturnLock($ren) !== true)
        {
            Db::rollback();
            return false;
        }
        $ren->status = PurchaseReturn::STATUS_RETURN_WAIT_OUT; // 待出库
        $ren->save();
        Db::commit();
        return true;
    }
}